package com.meatball.authorization.config

import com.meatball.core.config.TOKEN
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.springframework.data.redis.core.StringRedisTemplate
import org.springframework.security.core.Authentication
import org.springframework.security.web.authentication.logout.LogoutHandler
import org.springframework.stereotype.Component

@Component
class LogoutComponent(
    private val jwtComponent: JwtComponent,
    private val stringRedisTemplate: StringRedisTemplate
) : LogoutHandler {
    override fun logout(request: HttpServletRequest?, response: HttpServletResponse?, authentication: Authentication?) {
        val authHeader = request?.getHeader("Authorization")
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            return
        }
        val jwt = authHeader.substring(7).trim()
        // 获取用户名
        val username = jwtComponent.extractUsername(jwt)
        stringRedisTemplate.delete(TOKEN + username)
    }
}